package com.ruoyi.know.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.know.domain.Notes;
import com.ruoyi.know.domain.UserComments;
import com.ruoyi.know.domain.UserLikes;
import com.ruoyi.know.domain.UserNoteFavorites;
import com.ruoyi.know.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * 笔记Controller
 *
 * @author ruoyi
 * @date 2025-02-09
 */
@RestController
@RequestMapping("/know/notes")
public class NotesController extends BaseController
{
    @Autowired
    private INotesService notesService;
    @Autowired
    private IUserNoteFavoritesService userNoteFavoritesService;
    @Autowired
    private IUserLikesService userLikesService;
    @Autowired
    private IPointRecordsService pointRecordsService;
    @Autowired
    private SensitiveWordService sensitiveWordService;
    @Autowired
    private IUserCommentsService userCommentsService;


    /**
     * 查询笔记列表
     */
    @PreAuthorize("@ss.hasPermi('know:notes:list')")
    @GetMapping("/list")
    public TableDataInfo list(Notes notes)
    {
        startPage();
        List<Notes> list = notesService.selectNotesList(notes);
        for (Notes note : list){
            setNotes(note);
        }
        return getDataTable(list);
    }

    private void setNotes(Notes notes){
        Long noteId = notes.getNoteId();
        //计算收藏数量
        UserNoteFavorites userNoteFavorites = new UserNoteFavorites();
        userNoteFavorites.setNoteId(noteId);
        int countByFavorites = userNoteFavoritesService.getCountByFavorites(userNoteFavorites);
        notes.setFavoritesNum(countByFavorites);

        //计算点赞数量
        UserLikes userLikes = new UserLikes();
        userLikes.setLikeType(2L);
        userLikes.setInfoId(noteId);
        notes.setLikeNum(userLikesService.getCountByLikes(userLikes));

        //  计算评论数量
        UserComments userComments = new UserComments();
        userComments.setInfoId(noteId);
        userComments.setCommentType(2L);
        notes.setCommentNum(userCommentsService.getCountByComments(userComments));

        //判断是否已经点过赞
        userLikes.setUserId(getUserId());
        int countByLikes = userLikesService.getCountByLikes(userLikes);
        notes.setLike(countByLikes>0);
        //判断是否已经收藏
        userNoteFavorites.setUserId(getUserId());
        int countByFavourites = userNoteFavoritesService.getCountByFavorites(userNoteFavorites);
        notes.setCollected(countByFavourites > 0);
    }

    /**
     * 导出笔记列表
     */
    @PreAuthorize("@ss.hasPermi('know:notes:export')")
    @Log(title = "笔记", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Notes notes)
    {
        List<Notes> list = notesService.selectNotesList(notes);
        ExcelUtil<Notes> util = new ExcelUtil<Notes>(Notes.class);
        util.exportExcel(response, list, "笔记数据");
    }



    /**
     * 获取笔记详细信息
     */
    @PreAuthorize("@ss.hasPermi('know:notes:query')")
    @GetMapping(value = "/{noteId}")
    public AjaxResult getInfo(@PathVariable("noteId") Long noteId)
    {
        Notes notes = notesService.selectNotesByNoteId(noteId);
        setNotes(notes);
        return success(notes);
    }

    /**
     * 新增笔记
     */
    @PreAuthorize("@ss.hasPermi('know:notes:add')")
    @Log(title = "笔记", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Notes notes)
    {
        //替换敏感词
        String noteTitle = notes.getNoteTitle();
        String noteContent = notes.getNoteContent();
//        notes.setNoteTitle(sensitiveWordService.replaceSensitive(noteTitle));
//        notes.setNoteContent(sensitiveWordService.replaceWithImgTag(noteContent));
        //20250402 不替换敏感词
        notes.setNoteTitle(noteTitle);
        notes.setNoteContent(noteContent);
        notes.setUserId(getLoginUser().getUserId());
        notes.setCreatedAt(new Date());
        notes.setCreatedBy(getUsername());
        pointRecordsService.earnPoints(getUserId(),"发布笔记",true);
        return toAjax(notesService.insertNotes(notes));
    }

    /**
     * 修改笔记
     */
    @PreAuthorize("@ss.hasPermi('know:notes:edit')")
    @Log(title = "笔记", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Notes notes)
    {
        //替换敏感词
        String noteTitle = notes.getNoteTitle();
        String noteContent = notes.getNoteContent();
//        notes.setNoteTitle(sensitiveWordService.replaceSensitive(noteTitle));
//        notes.setNoteContent(sensitiveWordService.replaceWithImgTag(noteContent));
        //20250402 不替换敏感词
        notes.setNoteTitle(noteTitle);
        notes.setNoteContent(noteContent);
        notes.setUpdatedAt(new Date());
        notes.setUpdateBy(getUsername());
        return toAjax(notesService.updateNotes(notes));
    }

    /**
     * 上传附件
     * 由于已经与清空附件的接口合并，所以这里就不需要再考虑更新空的问题
     */
    @PreAuthorize("@ss.hasPermi('know:notes:uploadFile')")
    @Log(title = "笔记", businessType = BusinessType.UPDATE)
    @PutMapping("/uploadFile")
    public AjaxResult uploadNoteFile(@RequestBody Notes notes)
    {
        Notes newNotes = new Notes();
        newNotes.setNoteId(notes.getNoteId());
        newNotes.setAttachUrl(notes.getAttachUrl());
        // 只运用noteId对附件信息做更替
        return toAjax(notesService.updateNotes(newNotes));
    }

    /**
     * 删除笔记
     */
    @PreAuthorize("@ss.hasPermi('know:notes:remove')")
    @Log(title = "笔记", businessType = BusinessType.DELETE)
	@DeleteMapping("/{noteIds}")
    public AjaxResult remove(@PathVariable Long[] noteIds)
    {
        //减积分
        pointRecordsService.earnPoints(getUserId(),"发布笔记",false);
        return toAjax(notesService.deleteNotesByNoteIds(noteIds));
    }

    /**
     * 清空附件
     * @param
     * @return
     */
    @PreAuthorize("@ss.hasPermi('know:notes:cleanFile')")
    @Log(title = "清空笔记附件", businessType = BusinessType.UPDATE)
    @PutMapping("/cleanFile/{noteId}")
    public AjaxResult cleanFile(@PathVariable Long noteId)
    {
        // 根据笔记的id 删除笔记的附件
        return toAjax(notesService.setNullForAttachUrl(noteId));
    }


    @PreAuthorize("@ss.hasPermi('know:notes:visibility')")
    @Log(title = "笔记", businessType = BusinessType.UPDATE)
    @PutMapping("/visibility")
    public AjaxResult visibility(@RequestBody Notes notes)
    {
        notes.setIsVisibility(notes.getIsVisibility());
        return toAjax(notesService.updateNotes(notes));
    }
}
